/**
 *@author hxl
 *@version beta1.0
 *<code>
 *使用方法：在页面初始化完毕后调用simpleCodeHighLight()即可;
 *</code>
 */
var simpleCodeHighLight;
var simpleCodeHighLightPlugin;
(function(){
	var _CODEKEYWORDS ={
			'JAVA' : {
						kw_1   : ['char' , 'int','long','byte','short','double','float','boolean'],//基本类型
						kw_2   : ['void' , 'final' , 'package','import','class','interface','abstract','private','public' , 'protected' , 'static' , 'final' , 'extends' , 'implements' ,'volatile' ,'case' , 'throws' , 'throw'],       
						kw_3   : ['if' , 'for' ,'while' , 'switch' , 'catch'],
						kw_4   : ['((?:^\\s*)||(?:\\s+)||(?:;)||(?:\\}))(synchronized)((?:\\s+)||(?:\\())','((?:^\\s*)||(?:\\s+))(break)((?:\\s+)||(?:;))' ,'((?:^\\s*)||(?:\\s+)||(?:;))(default)((?:\\s+)||(?:\\:))' ,'((?:^\\s*)||(?:\\s+)||(?:=)||(?:\\.))(new)(\\s+)' , '((?:\\})||(?:\\s+))(else)((?:\\{)||(?:\\s+))','((?:^\\s*)||(?:\\s+)||(?:;))(try)((?:\\s+)||(?:\\{))','((?:\\})||(?:\\s+))(finally)((?:\\{)||(?:\\s+))','((?:^\\s*)||(?:\\s+))(return)((?:\\s+)||(?:\\;))']//特殊关键字
					},
			'JAVASCRIPT' : {
						kw_1   : ['var'],
						kw_2   : [],
						kw_3   : ['if' , 'for' ,'while' , 'switch' , 'catch' ,'function'],
						kw_4   : ['((?:^\\s*)||(?:\\s+))(break)((?:\\s+)||(?:;))' ,'((?:^\\s*)||(?:\\s+)||(?:;))(default)((?:\\s+)||(?:\\:))' ,'((?:^\\s*)||(?:\\s+)||(?:=)||(?:\\.))(new)(\\s+)' , '((?:\\})||(?:\\s+))(else)((?:\\{)||(?:\\s+))','((?:^\\s*)||(?:\\s+)||(?:;))(try)((?:\\s+)||(?:\\{))','((?:\\})||(?:\\s+))(finally)((?:\\{)||(?:\\s+))','((?:^\\s*)||(?:\\s+))(return)((?:\\s+)||(?:\\;))']//特殊关键字
					},
			'C'	:	{
						kw_1   : ['char' , 'int','long','byte','short','double','float','boolean'],//基本类型
						kw_2   : ['void'],
						kw_3   : ['if' , 'for' ,'while' , 'switch' , 'catch'],
						kw_4   : ['(\\s*)(\\#include)(\\s*\\&lt;)','((?:^\\s*)||(?:\\s+))(return)((?:\\s+)||(?:\\;))']
					}
	};
	var codeHTMLArray =["<ol>"];//代码
	var __com_flag = 0;//1:代码注释；2：文档注释;3：单行注释
	function formatter(codeObject , lang){
		var codeStr =codeObject.innerHTML;
		var LANG_KWS = _CODEKEYWORDS[lang.toUpperCase()];
		var splitCode = codeStr.split('\n');
		for(var i=0,len=splitCode.length ; i < len ; ++i){
			var rowCode = splitCode[i];
			var tmp = com(rowCode);
			if(tmp=='undefined'){
				var strindex = s(rowCode);
				var start=strindex['start'];
				var end=strindex['end'];
				if(start.length>0){
					var tmpCodeRow=[];
					for(var j=0,len2=start.length;j<len2;++j){
						var _start=(j==0?0:start[j-1]);
						tmpCodeRow.push(k_4(k_3(k_2(k_1(rowCode.substring(_start , start[j]),LANG_KWS['kw_1']),LANG_KWS['kw_2']),LANG_KWS['kw_3']),LANG_KWS['kw_4']));
						tmpCodeRow.push('<span class=str>'+rowCode.substring(start[j] , end[j]?(end[j]+1):rowCode.length)+'</span>');
						if(!end[j] && end[j]+1==rowCode.length){
							break;
						}
						tmpCodeRow.push(k_4(k_3(k_2(k_1(rowCode.substring(end[j]+1 , start[j+1]?start[j+1]:rowCode.length),LANG_KWS['kw_1']),LANG_KWS['kw_2']),LANG_KWS['kw_3']),LANG_KWS['kw_4']));
					}
					rowCode=tmpCodeRow.join('');
				}else{
					rowCode=k_4(k_3(k_2(k_1(rowCode , LANG_KWS['kw_1']) ,LANG_KWS['kw_2']),LANG_KWS['kw_3']),LANG_KWS['kw_4']);
				}
			}else{
				rowCode = tmp;
			}
			if(i&1==1){
				codeHTMLArray.push("<li>");
			}else{
				codeHTMLArray.push("<li class=odd>");
			}
			codeHTMLArray.push(rowCode);
			codeHTMLArray.push("</li>");
		}
	}
    
	/**
	 *字符串处理
	 */
	function s(c){
		var is=0;//1：单引号；2：双引号
		var start=[];
		var end=[];
		for(var i=0,len=c.length;i<len;++i){
			var ch = c.charAt(i);
			if(is==0 && (ch=="\"" || ch=='\'') && c.charAt(i-1) !='\\'){
			//	alert('test');
				if(ch=="\""){
					is=1;
				}else if("\'"){
					is=2;
				}
				start.push(i);
			}else if(((is==1 && ch=="\"")||(is==2&&ch=='\'')) && c.charAt(i-1) !='\\'){
				is=0;
				end.push(i);
			}else if(is==0 && ch=='/'){//单行注释
				if(c.charAt(i-1) && c.substring(i-1,i+1)=="//"){
					var _i = i-1;
					var t_num=0;
					while(--_i>=0){
						if(c.charAt(_i)=='\\') ++t_num;
						else break;
					}
					if(t_num&1==1){//奇数
						continue;
					}else{
						start[0]=(i-1);
						end[0]=(c.length-1);
						return {'start':start,'end':end};//结束
					}
				}
			}
		}
		return {'start':start,'end':end};
	}
    
	function k_1(c , keywords){
		for(var i=0 , len=keywords.length;i<len;++i){
			var regExp = new RegExp('((?:^\\s*)|(?:\\s+)|(?:;))('+keywords[i]+')((?:\\s+)|(?:\\s*\\[))',"g");
			c=c.replace(regExp , '$1<span class=kwd>$2</span>$3');
		}
		return c;
	}

	function k_2(c , kws){
		for(var i=0,len=kws.length;i<len;++i){
			var regExp = new RegExp('((?:^\\s*)||(?:\\s+))('+kws[i]+')(\\s+)','g');
			c=c.replace(regExp , '$1<span class=kwd>$2</span>$3');
		}
		return c;
	}

	function k_3(c , kws){
		for(var i=0,len=kws.length;i<len;++i){
			var regExp = new RegExp('((?:^\\s*)||(?:\\s+)||(?:;)||(?:\\{||\\}))('+kws[i]+')((?:\\s+)||(?:\\())','g');
			c=c.replace(regExp , '$1<span class=kwd>$2</span>$3');
		}
		return c;
	}

	function k_4(c , kws){
		for(var i=0,len=kws.length;i<len;++i){
			var regExp = new RegExp(kws[i]);
			c=c.replace(regExp , '$1<span class=kwd>$2</span>$3');
		}
		return c;
	}

	function com(c){
		var tmpCode = c.replace(/^\s*|\s*$/g , '');
		var flag = false;
		if(__com_flag==0 && tmpCode.substring(0,2)=='/*'){
			if(tmpCode.substring(2,3)=='*'){
				c ='<span class=dcom>'+label(c)+'</span>';
				__com_flag=2;

			}else{
				c ='<span class=com>'+c+'</span>';
				__com_flag=1;
			}
			flag=true;
		}else if(__com_flag==1 || __com_flag==2){
			if(__com_flag==1){
				c ='<span class=com>'+c+'</span>';
			}else if(__com_flag==2){
				c ='<span class=dcom>'+label(c)+'</span>';
			}
			if(tmpCode.substring(tmpCode.length-2,tmpCode.length)=='*/'){
				__com_flag=0;
			}
			flag = true;
		}
        if(flag){
			return c;
		}
		return 'undefined';
	}
	
	function label(c){
		c = c.replace(/&lt;/gm,'<');
		c = c.replace(/&gt;/gm ,'>');
		c = c.replace(/(\<([^\>]+)\>.*\<\/\2\>)/g , '&ltt;span class=tag&gtt;$1&ltt;/span&gtt;');
		c = c.replace(/</gm ,'&lt;');
		c = c.replace(/>/gm , '&gt;');
		c = c.replace(/&ltt;/gm,'<');
		c = c.replace(/&gtt;/gm ,'>');
		return c;
	}
     
	function replaceCodeHTML(codeObject , lang){
		codeHTMLArray.push("</ol>");
		codeObject.innerHTML ='<div>'+lang+' code</div>'+ codeHTMLArray.join('');
		codeHTMLArray =["<ol>"];//初始化数组
	}

	function formatCode(code){
		var codes=[];
		if(arguments.length==0){
			codes=document.getElementsByTagName("PRE");
		}else{
			codes[0]=stringToXML(code);
			codes[0].className=codes[0].childNodes[0].attributes[0].nodeValue;
			codes[0].innerHTML=codes[0].childNodes[0].textContent;
		}
		for(var i=0 , len=codes.length ; i < len ; ++i){
			var codeObject = codes[i];
			var className = codeObject.className;
			var regExp = /.*\slang-(java||c#||javascript||c)(?:(?:\s+.*)||(?:\s*))/g;
            var lang  = className.replace(regExp , '$1');//提取语言
			formatter(codeObject,lang);//格式化代码
			replaceCodeHTML(codeObject , lang);//替换网页中得代码
		}
	}

	function stringToXML(xmlData){  
		if (window.ActiveXObject) {  
				//for IE  
               xmloc = new ActiveXObject("Microsoft.XMLDOM");  
               xmlDoc.async = "false";  
               xmlDoc.loadXML(xmlData);  
               return xmlDoc;  
          }  
         else  if (document.implementation && document.implementation.createDocument) {  
             //for Mozila  
              parser = new DOMParser();  
              xmlDoc = parser.parseFromString(xmlData, "text/xml");  
              return xmlDoc;  
         }  
    }  
	window['simpleCodeHighLight']=formatCode;
})();